<template>
    <div class="component">
    <Breadcrumb :menulist="[`${componentType == 1 ? '项目' : '产品'}`, '组件']" v-on:changeSolution="changeSolution" :componentType="componentType"></Breadcrumb>

    <el-card class="box-card" shadow="hover">
      <div slot="header" class="tabHeader">
          <el-button class="openComp" type="text" @click="showSelectComp">打开组件库</el-button>
          <span>
            {{componentSelect}}
          </span>
          <el-button class="addPro" icon="el-icon-circle-plus" type="primary" @click="showAddPro">添加组件</el-button>
      </div>
      <el-table
            :data="tableData"
            max-height="600"
            line-height="50"
            border
            :header-cell-style='headerStyle'
            style="width: calc(100% - 40px); margin: 0 20px;">
            <!--
              <el-table-column
                  prop="componentId"
                  label="组件ID"
                  width="100"
                  align="center">
              </el-table-column>
            -->
            <el-table-column
                prop="componentCode"
                label="组件编码"
                width="200"
                align="center">
            </el-table-column>
            <el-table-column
                prop="componentName"
                align="center"
                width="200"
                label="组件名称">
            </el-table-column>
            <el-table-column
                prop="packageName"
                align="center"
                width="100"
                label="包名">
            </el-table-column>
            <el-table-column
                prop="moduleName"
                align="center"
                width="200"
                label="所属模块">
            </el-table-column>
            <el-table-column
                prop="solutionName"
                align="center"
                width="200"
                v-if="componentType === 1"
                label="所属项目">
            </el-table-column>
            <el-table-column
                prop="topSolutionName"
                align="center"
                width="100"
                label="所属产品">
            </el-table-column>
            <el-table-column
                prop="createTime"
                align="center"
                width="100"
                label="创建时间">
            </el-table-column>
            <el-table-column
                prop="createUserName"
                align="center"
                width="100"
                label="创建用户">
            </el-table-column>
            <el-table-column
                prop="modifyTime"
                align="center"
                width="100"
                label="修改时间">
            </el-table-column>
            <el-table-column
                prop="modifyUserName"
                align="center"
                width="100"
                label="修改用户">
            </el-table-column>
            <el-table-column
                prop="description"
                align="center"
                width="100"
                label="描述">
            </el-table-column>
            <el-table-column
                align="center"
                width="160"
                label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button size="mini" slot="reference" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

     </el-card>

    <el-drawer
      title="组件库"
      :visible.sync="showComp"
      direction="ltr"
      :with-header="false"
      size="30%">
      <div class="drawerTitle">选择组件库</div>
      <el-tree
        :data="treeData"
        node-key="id"
        class="tree"
        :props="treedefaultProps"
        @node-click="handleNode">
      </el-tree>

    </el-drawer>
 
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="slot, total, sizes, prev, pager, next, jumper"
      :total="total">
        <el-button icon="el-icon-refresh" type="primary" style="margin-right: 10px; background: #409EFF; color:#fff" @click="getComponentsList"></el-button>
    </el-pagination>

    <!-- 添加项目解决方案 -->
    <el-dialog :title="dialogTitle"  :visible.sync="dialogFormVisible" width="60%" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item v-if="dialogTitle === '删除组件'" label="删除提示信息">
          <div style="color: #d93a49;">{{deleteCheckContent}}</div>
        </el-form-item>
        <el-form-item label="组件编码" prop="componentCode">
          <el-input v-model="form.componentCode" placeholder="请输入组件编码" :disabled="dialogTitle !== '添加组件'"></el-input>
        </el-form-item>
        <el-form-item label="组件名称" prop="componentName">
          <el-input v-model="form.componentName" placeholder="请输入组件名称" :disabled="deleteDisabled"></el-input>
        </el-form-item>
        <!--
             <el-form-item label="包名" prop="packageName">
            <el-input v-model="form.packageName" placeholder="请输入包名" :disabled="dialogTitle !== '添加组件'"></el-input>
          </el-form-item>
        -->
        <el-form-item label="所属模块" prop="moduleName" v-if="componentType===1">
          <el-input v-model="form.moduleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属项目" prop="solutionName">
          <el-input v-model="form.solutionName" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属产品" prop="topSolutionName">
          <el-input v-model="form.topSolutionName" disabled></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" :disabled="deleteDisabled" placeholder="请输入描述" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="dialogTitle === '添加组件'" @click="handleSave('form')">保 存</el-button>
        <el-button type="primary" v-if="dialogTitle === '编辑组件'" @click="__handleEdit('form')">保 存</el-button>
        <el-button type="primary" plain v-if="dialogTitle === '添加组件'" @click="resetForm('form')">清 除</el-button>
        <el-button type="danger" plain v-if="dialogTitle === '删除组件'" @click="__handleDelete('form')">删 除</el-button>
        <el-button @click="handleCancel('form')">取 消</el-button>
      </div>
    </el-dialog>
    </div>
</template>


<script>

import {request, url} from "@/api/request";
import Breadcrumb from "@/components/Breadcrumb.vue";

export default {
  name: "componentd",
  components: {
    Breadcrumb
  },
  props: {
    componentType: {
        type: Number,
        default: 1,//1组件，2产品
    },
  },
  data() {
    return {
      headerStyle: {
        "line-height": "40px"
      },
      tableData: [],
      formLabelWidth: "100px",
      dialogFormVisible: false,
      form: {
        proCode: "",
        proName: "",
        proType: "项目",
        proVersion: "",
        databaseName: "",
        partPro: "",
        describe: "",
        componentCode: "",  // 组件code
        componentName: "",  //  组件名称
        // packageName: "",  //  包名
        moduleId: "",   //  所属模块Id
        moduleName: "",   //  模块名称
        solutionId: "",   //  所属项目Id
        solutionName: "",   //  所属项目名称
        topSolutionID: "",    //  所属产品Id
        topSolutionName: "", //  所属产品
        description: "",  //  描述
        solutionCode: "", 
        moduleCode: "",
        componentId: ""
      },
      rules: {
        componentCode: [
          { required: true, message: '请输入组件编码', trigger: 'change' },
        ],
        componentName: [
          { required: true, message: '请输入组件名称', trigger: 'change' },
        ],
      },
      showComp: false,
      treeData: [],
      treedefaultProps: {
        children: 'childs',
        label: 'label'
      },
      componentSelect: '-',
      pageNum: 0,
      pageSize: 10,
      total: 0,
      dialogTitle: '添加组件',
      deleteDisabled: false,
      deleteCheckContent: "",
      defaultModule: "",  // 默认模块id
    };
  },

  created() {
    if (this.$store.state.solution_global) {
      this.getTreesList();
    }
  },
  methods: {
    // 切换 solution 
    changeSolution() {
      this.getTreesList();
    },
    // 组件数 tree
    getTreesList() {
      let solutionId = this.$store.state.solution_global.solutionId;
      request(`${url.navigationtree}/${solutionId}`,{
        method:'GET',
        data: {}
      },res=>{
        let newData = res.data.root.childs;
        console.log(newData)
        if (!newData) {
          return false;
        }
        let treedata = [];
        newData.map((item, i) => {
          if(item.childs) {
            item.childs.map((cell, j) => {
              cell.disabled = true
              if (cell.navigationType.displayName === 'Component') {
                delete cell.childs
              }
            })
          }
        })
        // this.treeData = newData;
        let d = this.filterTree(newData);
        this.treeData = d;
        
      })
    },

    // 过滤 tree 数据重新整合
    filterTree(data) {
      return data.map(item => {
        if (item.childs) {
          this.filterTree(item.childs);
        }
        item.label = `${item.label}（${item.navigationType.displayName}）`
        return item;
      }).filter(item => item);
    },

    // 查询列表
    getComponentsList() {
     if (!this.$store.state.solution_global) {
        return this.$message({
          message: '请先选择一个解决方案',
          type: 'warning'
        });
      }
      if (this.defaultModule === '') {
        return this.$message({
          message: '请先选择一个模块',
          type: 'warning'
        });
      }

      let moduleId = this.defaultModule;
      let solutionId = this.$store.state.solution_global.solutionId;
      let params = {
        currentPage: this.pageNum,
        rows: this.pageSize,
        solutionId: solutionId
      }
      request(`${url.componentsList}/${moduleId}`,{
          method:'GET',
          data: params
      },res=>{
          this.tableData = res.data.list;
          this.pageNum = res.data.pageNum;
          // this.pageSize = res.data.pageSize;
          this.total = res.data.total;
      })
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.getComponentsList();
    },
    
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getComponentsList();
    },

    showAddPro() {
      if (!this.$store.state.solution_global) {
        return this.$message({
          message: '请先选择一个解决方案',
          type: 'warning'
        });
      }
      if (this.defaultModule === '') {
        return this.$message({
          message: '请先选择一个模块',
          type: 'warning'
        });
      }
      this.dialogTitle = '添加组件';
      this.dialogFormVisible = true;
      this.deleteDisabled = false;
      this.form.moduleId = '';
      this.form.moduleName = '';
      this.form.solutionId = '';
      this.form.solutionName = '';
      this.form.topSolutionId = '';
      this.form.topSolutionName = '';
      this.form.solutionCode = '';
      this.form.moduleCode = '';
      this.form.componentCode = '';
      this.form.componentName = '';
      this.form.description = '';
      // this.form.packageName = '';
      this.form.componentId = '';

      this.getComponentsDefault();
    },

    showSelectComp() {
      this.showComp = true
    },

    handleNode(data, parent) {

      if (data.navigationType.displayName === "Module") {
        this.showComp = false;
        this.componentSelect = ""; //  初始化
        this.defaultModule = data.id; //  设置选中的module
        this.getTreeNode(parent);
        this.getComponentsList();
      } else {
        this.$message({
          message: '请先选择模块',
          type: 'warning'
        });
      }

    },

    //获取当前树节点和其父级节点
    getTreeNode(node){
      if (node.parent) {
          this.componentSelect = `${node.label} ${this.componentSelect ? '>':''} ${this.componentSelect}`;
          this.getTreeNode(node.parent); //递归
      }
    },

    // 获取默认组件
    getComponentsDefault() {
      request(`${url.componentsDefault}/${this.defaultModule}`,{
          method:'GET',
          data: {}
        },res=>{
          let data = res.data;
          this.form.moduleId = data.moduleId;
          this.form.moduleName = data.moduleName;
          this.form.solutionId = data.solutionId;
          this.form.solutionName = data.solutionName;
          this.form.topSolutionId = data.topSolutionId;
          this.form.topSolutionName = data.topSolutionName;
          this.form.solutionCode = data.solutionCode;
          this.form.moduleCode = data.moduleCode;
        })
    },

    // 保存
    handleSave(formName) {
      console.log(this.form)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let parmas = {
            componentCode: this.form.componentCode,  // 组件code
            componentName: this.form.componentName,  //  组件名称
            solutionCode: this.form.solutionCode, //  模块
            solutionId: this.form.solutionId,   //  所属项目Id
            description: this.form.description,  //  描述
            moduleId: this.form.moduleId,
            moduleCode: this.form.moduleCode,
            topSolutionId: this.form.topSolutionId
          };
          request(`${url.components}`,{
              method:'POST',
              data: parmas
          },res=>{
              this.$message({
                message: res.message,
                type: 'success'
              });
              this.dialogFormVisible = false;
              this.getComponentsList();
              this.$refs.form.resetFields();  // 重置 form表单
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.form.componentCode = "";  // 组件code
      this.form.componentName = "";  //  组件名称
      this.form.description = "";
    },

    handleCancel(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisible = false;
    },

    // 编辑
    handleEdit(index, row) {
      console.log(row);
      this.dialogTitle = '编辑组件';
      this.dialogFormVisible = true;
      this.form.moduleId = row.moduleId;
      this.form.moduleName = row.moduleName;
      this.form.solutionId = row.solutionId;
      this.form.solutionName = row.solutionName;
      this.form.topSolutionId = row.topSolutionId;
      this.form.topSolutionName = row.topSolutionName;
      this.form.solutionCode = row.solutionCode;
      this.form.moduleCode = row.moduleCode;
      this.form.componentCode = row.componentCode;
      this.form.componentName = row.componentName;
      this.form.description = row.description;
      // this.form.packageName = row.packageName;
      this.form.componentId = row.componentId;

    },

    __handleEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.form)
          let parmas = {
            componentCode: this.form.componentCode,  // 组件code
            componentName: this.form.componentName,  //  组件名称
            solutionCode: this.form.solutionCode, //  模块
            solutionId: this.form.solutionId,   //  所属项目Id
            description: this.form.description,  //  描述
            moduleId: this.form.moduleId,
            moduleCode: this.form.moduleCode,
            topSolutionId: this.form.topSolutionId
          };
          console.log(parmas)
          request(`${url.components}/${this.form.componentId}`,{
              method:'PUT',
              data: parmas
          },res=>{
              this.$message({
                message: res.message,
                type: 'success'
              });
              this.dialogFormVisible = false;
              this.getComponentsList();
              this.$refs.form.resetFields();  // 重置 form表单
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 删除
    handleDelete (index, row) {
      console.log(row)
      this.dialogTitle = '删除组件';
      this.deleteDisabled = true;
      this.dialogFormVisible = true;

      this.form.moduleId = row.moduleId;
      this.form.moduleName = row.moduleName;
      this.form.solutionId = row.solutionId;
      this.form.solutionName = row.solutionName;
      this.form.topSolutionId = row.topSolutionId;
      this.form.topSolutionName = row.topSolutionName;
      this.form.solutionCode = row.solutionCode;
      this.form.moduleCode = row.moduleCode;
      this.form.componentCode = row.componentCode;
      this.form.componentName = row.componentName;
      this.form.description = row.description;
      // this.form.packageName = row.packageName;
      this.form.componentId = row.componentId;
      this.deleteCheck(row.componentId);
      
    },

    // check delete
    deleteCheck(componentId) {
      request(`${url.componentsDeleteCheck}/${componentId}`,{
          method:'GET',
          data: {}
      },res=>{
        this.deleteCheckContent = res.data + res.message;
      })
    },

    //  确认删除 
    __handleDelete () {
      let componentId = this.form.componentId;
      request(`${url.components}/${componentId}`,{
          method:'DELETE',
          data: {}
      },res=>{
          this.dialogFormVisible = false;
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.getComponentsList();
          this.$refs.form.resetFields();  // 重置 form表单
      })
    }
  }
};
</script>

<style scoped>
.addPro {
  float: right;
}

.openComp {
  margin-left: 20px;
}

.drawerTitle {
  line-height: 70px;
  font-size: 20px;
  margin-left: 30px;
}

.tree {
  margin-left: 30px;
  
}
</style>
